package com.neolix.watch.weather;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.neolix.watch.NeolixNaviagationBaseActivity;
import com.neolix.watch.R;
import com.neolix.watch.adapter.WeatherAdapter;
import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.domain.BaiDuWeatherResult;
import com.neolix.watch.domain.WeatherType;
import com.neolix.watch.util.ByteUtil;
import com.neolix.watch.util.Constant;
import com.neolix.watch.util.FontTypefaceUtil;
import com.neolix.watch.util.SharedPreferencesUtil;
import com.neolix.watch.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import static com.neolix.watch.domain.WeatherType.findCommandType;
import static com.neolix.watch.service.BackgroundTaskService.submitTask;
import static com.neolix.watch.util.DateTimeUtil.isDay;
import static com.neolix.watch.util.StringUtil.createDrawableUrl;
import static com.neolix.watch.util.StringUtil.formatTimeToMonthAndDayString1;
import static com.neolix.watch.util.StringUtil.showText;

public class WeatherActivity extends NeolixNaviagationBaseActivity {

    private IntentFilter filter;
    private BroadcastReceiver receiver;
    private GridView gridView;
    private boolean hadCreateGridView;
    private int itemHeight;
    private WeatherAdapter adapter;
    private ImageView currentWeatherImnage;
    private TextView currentTemperature;
    private TextView currentWeatherConditionText;
    private TextView currentDataText;
    private TextView currentWeek;
    private DisplayImageOptions options;
    private ImageLoader imageLoader;

    public WeatherActivity() {
        super(R.layout.activity_weather);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initUi();
        initListener();
        initBroadcastReceiver();
        initImageLoader();

        setTitle(getString(R.string.unknow));
        submitTask(getApplicationContext(), UpdateLocationTask.class);
    }

    private void loadOldWeatherInfo() {
        BaiDuWeatherResult weatherResult = SharedPreferencesUtil.getWeatherInfo();
        if (weatherResult != null)
            updateUi(weatherResult);
    }

    private void initUi() {
        gridView = (GridView) findViewById(R.id.weather_gridView);

        currentWeatherImnage = (ImageView) findViewById(R.id.weather_condition_imageView);
        currentTemperature = (TextView) findViewById(R.id.current_temperature);
        currentWeatherConditionText = (TextView) findViewById(R.id.weather_condition_text);
        currentDataText = (TextView) findViewById(R.id.current_date);
        currentWeek = (TextView) findViewById(R.id.current_week);

        FontTypefaceUtil.setTypefaceOfHelvetica(currentTemperature);
    }

    private void initImageLoader() {
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        imageLoader = ImageLoader.getInstance();
    }

    private void initListener() {
        ViewTreeObserver vto = gridView.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (hadCreateGridView) {
                    return true;
                }
                itemHeight = gridView.getHeight();
                adapter = new WeatherAdapter(getApplicationContext(), itemHeight);
                adapter.bindListView(gridView);
                loadOldWeatherInfo();
                hadCreateGridView = true;
                return true;
            }
        });
    }

    private void initBroadcastReceiver() {
        filter = new IntentFilter();
        filter.addAction(Constant.COM_NEOLIX_WATCH_LOCATION_CHANGE);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (SharedPreferencesUtil.getCurrentLocation() != null)
                    queryWeatherInfo();
                else
                    showText(getString(R.string.query_weather_info_failure));
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.getApplication().registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onStop();
        this.getApplication().unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imageLoader.clearDiscCache();
    }

    private void queryWeatherInfo() {
        new RequestWeatherAsyncTask() {
            @Override
            public void OnResponse(BaiDuWeatherResult httpResponse) {
                if (httpResponse == null) {
                    showText(getString(R.string.query_weather_info_failure));
                    return;
                }

                updateUi(httpResponse);
            }
        }.sendRequest();
    }

    private void updateUi(BaiDuWeatherResult result) {
        if (!result.isCorrectResults()) {
            showText(getString(R.string.query_weather_info_failure));
            return;
        }

        BaiDuWeatherResult.BaiDuWeatherData currentWeatherInfo = result.getCurrentWeatherInfo();
        setTitle(result.getCurrentCity());
        BlueToothUtil.syncWeather(currentWeatherInfo.getWeather(), result.getCurrentTemperatureValue());
        imageLoader.displayImage(isDay() ? createDrawableUrl(findCommandType(currentWeatherInfo.getWeather()).getDayBigPictureId()) :
                        createDrawableUrl(findCommandType(currentWeatherInfo.getWeather()).getNightBigPictureId()),
                currentWeatherImnage, options
        );
        currentWeatherConditionText.setText(currentWeatherInfo.getWeather());
        currentTemperature.setText(result.getCurrentTemperature());
        currentWeek.setText(result.getCurrentWeek());
        currentDataText.setText(formatTimeToMonthAndDayString1(currentWeatherInfo.getDateTime()));

        gridView.setNumColumns(result.getFutureWeatherList().size());
        adapter.setData(result.getFutureWeatherList());
    }
}
